<?php
/**
* @author moufer<moufer@163.com>
* @copyright (c)2001-2014 Moufersoft
* @website www.modoer.com
*/

!defined('IN_MUDDER') && exit('Access Denied');

/**
* 微站模型
*/
class msm_weixin_site extends ms_model
{
	public $table = 'dbpre_weixin_site';
	public $key = 'id';
	public $model_flag = 'weixin';

	public function __construct()
	{
		parent::__construct();
		$this->model_flag = 'weixin';
		$this->modcfg = $this->variable('config');
		$this->init_field();
	}

	/**
	 * 表单提交时需要的字段和过滤
	 */
	public function init_field()
	{
		//$this->add_field('mp_id,sid,config,navs,pics,status,template_id');
	}

	public function read_by_sid($sid)
	{
		return $this->db->from($this->table)
			->where('sid', $sid)
			->get_one();
	}

	public function read_by_mp_id($mp_id)
	{
		return $this->db->from($this->table)
			->where('mp_id', $mp_id)
			->get_one();
	}

	public function save_config($post, $id = null)
	{
		static $post_fields = array('mp_id','sid','name','tel','address','status');
		static $config_fields = array('name','tel','address');
		if($id > 0) {
			$detail = $this->read($id);
			if(!$detail) return $this->add_error('对不起，您指定的微站不存在。');
		}

		foreach ($post as $key => $value) {
			if(!in_array($key, $post_fields)) {
				unset($post[$key]);
			} else {
				$post[$key] = _T($value);
			}
		}
		if(!$this->in_admin) $post['status'];
		if($id) unset($post['sid']);

		if(!$post['name']) return $this->add_error('对不起，您未填写微站名称。');
		if(!$id) {
			if(!$post['sid']) return $this->add_error('对不起，您未指定微站所属商户。');
			$subject = _G('loader')->model('item:subject')->read($post['sid']);
			if(!$subject) return $this->add_error('对不起，微站商户不存在。');
		}

		$array = array();
		foreach ($config_fields as $key) {
			$array[$key] = $post[$key];
			unset($post[$key]);
		}
		$post['config'] = ms_mxml::from_array($array);
		$this->db->from($this->table)->set($post);
		if($id) {
			$this->db->where('id',$id)->update();
		} else {
			$this->db->insert();
			$id = $this->db->insert_id();
		}
		return $id;
	}

	public function save_navs($id, $navs)
	{
		$this->save_pic_and_link($id, $navs, 'navs');
	}

	public function save_pics($id, $pics)
	{
		$this->save_pic_and_link($id, $pics, 'pics');
	}

	/**
	 * 设置微信的模板
	 * @param integer $id          [description]
	 * @param [type] $template_id [description]
	 */
	public function set_template($id, $template_id)
	{
		$tpl_mdl = _G('loader')->model('template');
		$tpl = $tpl_mdl->read($template_id);
		if(!$tpl||$tpl['tpltype']!='weixin') {
			return $this->add_error('您选择的模板不存在或者不是一个有效的微信微站模板。');
		}
		$this->db->from($this->table)
			->where('id', $id)
			->set('template_id', $template_id)
			->update();
		return true;
	}

	/**
	 * 删除微站数据
	 * @param  integer $id 微站ID
	 * @return boolean
	 */
	public function delete($id)
	{
		$data = $this->read($id);
		return $this->_delete($data);
	}

	public function delete_by_sid($sid)
	{
		$data = $this->read_by_sid($sid);
		return $this->_delete($data);
	}

	//保存菜单图片和幻灯片
	protected function save_pic_and_link($id, $array, $fieldname) 
	{
		static $fields = array('title', 'url', 'picurl');
		
		$detail = $this->read($id);

		foreach ($array as $key => $value) {
			foreach ($value as $_key => $_value) {
				//删除未定义的字段
				if(!in_array($_key, $fields)) {
					unset($value[$_key]);
					continue;
				}
				$value[$_key] = _T($_value);
				if(!$value[$_key]) return $this->add_error('对不起，表单项不能为空（标题，链接和图片）。');
			}
			if(strposex($value['picurl'], '/temp/')) {
				$picurl = $this->move_local_picture($value['picurl']);
				$array[$key]['picurl'] = $picurl?$picurl:'';
			}
		}
		$post = array();
		$post[$fieldname] = ms_mxml::from_array($array);
		$this->db->from($this->table)->set($post)->where('id',$id)->update();

		$old_navs = ms_mxml::to_array($detail[$fieldname]);
		if($old_navs) foreach ($old_navs as $key => $value) {
			$del = true;
			foreach ($array as $k => $v) {
				if($v['picurl']==$value['picurl']) $del=false; //新旧对比，如果新提交不存在的，就进行删除
			}
			if($del && strlen($value['picurl']) > 10) @unlink(MUDDER_ROOT.$value['picurl']);
		}
		return true;
	}

	//把上传临时文件夹的图片移动到正式保存文件夹
	protected function move_local_picture($pic)
	{
		$sorcuefile = MUDDER_ROOT . $pic;
		if(!is_file($sorcuefile)) {
			return false;
		}
		if(function_exists('getimagesize') && !@getimagesize($sorcuefile)) {
			@unlink($sorcuefile);
			return false;
		}

		$IMG = new ms_image();
		$IMG->thumb_mod = S('picture_createthumb_mod');

		$path = 'uploads';
		$name = basename($sorcuefile);
		$picture_dir_mod = S('picture_dir_mod');
		if($picture_dir_mod == 'WEEK') {
			$subdir = date('Y', _G('timestamp')) . '-week-' . date('W', _G('timestamp'));
		} elseif($picture_dir_mod == 'DAY') {
			$subdir = date('Y-m-d', _G('timestamp'));
		} else {
			$subdir = date('Y-m', _G('timestamp'));
		}

		$subdir = 'weixin' . DS . $subdir;
		$dirs = explode(DS, $subdir);
		foreach ($dirs as $val) {
			$path .= DS . $val;
			if(!@is_dir(MUDDER_ROOT . $path)) {
				if(!mkdir(MUDDER_ROOT . $path, 0777)) {
					show_error(lang('global_mkdir_no_access',$path));
				}
			}
		}
		$result = array();
		$filename = $path . DS . $name;
		$picture = str_replace(DS, '/', $filename);
		if(!copy($sorcuefile, MUDDER_ROOT . $filename)) {
			return false;
		}

		if(!DEBUG) @unlink($sorcuefile);
		return $picture;
	}

	protected function _delete($data)
	{
		if(!$data) return;
		$pics = array();
		foreach (array('navs','pics') as $key) {
			if($data[$key]) {
				$arr = ms_mxml::to_array($data[$key]);
				if($arr) foreach ($arr as $val) {
					$pics[] = str_replace('/', DS, $val['picurl']);
				}
			}
		}
		if($pics) foreach ($pics as $pic) {
			if(strlen($pic) > 4 && is_file(MUDDER_ROOT.$pic)) {
				@unlink(MUDDER_ROOT.$pic);
			}
		}
		$this->db->from($this->table)
			->where('id', $data['id'])
			->delete();
	}

}

/* end */